package club.westudy.distributed.lock;

import club.westudy.distributed.lock.internal.InternalLockExecutorService;

public class DefaultDistributedLockService implements DistributedLockService{
    InternalLockExecutorService internalLockExecutorService;
    @Override
    public void init() {

    }

    @Override
    public void shutdownNow() {

    }

    @Override
    public void shutdown(boolean force) {

    }

    @Override
    public boolean obtain(String feature, long maxLeaseTimeMs, long tryLockWaitTimeMs) {
        // 1.通过内部实现的分布式锁服务进行获取锁，返回临界区上下文
        DistributedLockService.CriticalRegionContext criticalRegionContext = internalLockExecutorService.acquire(feature, maxLeaseTimeMs, tryLockWaitTimeMs);
        // 2.将临界区上下文向会话中注册
        return false;
    }

    @Override
    public boolean execute(String feature, CriticalRegionRunnable criticalRegionRunnable, long maxLeaseTimeMs, long tryLockWaitTimeMs) {
        // 1.通过内部实现的分布式锁服务进行获取锁，返回临界区上下文
        DistributedLockService.CriticalRegionContext criticalRegionContext = null;
       try {
           criticalRegionContext = internalLockExecutorService.acquire(feature, maxLeaseTimeMs, tryLockWaitTimeMs);
           criticalRegionRunnable.before(criticalRegionContext);
           criticalRegionRunnable.run(criticalRegionContext);
           criticalRegionRunnable.after(criticalRegionContext);
           return true;
       } catch (Throwable throwable) {
           return false;
       } finally {
            if (criticalRegionContext != null){
                internalLockExecutorService.release(criticalRegionContext);
            }
       }
    }

    @Override
    public boolean release(String feature) {
        // 1.根据锁特征从会话中获取临界区上下文
        DistributedLockService.CriticalRegionContext criticalRegionContext = null;
        // 2.调用内部实现分布式锁服务进行锁释放
        internalLockExecutorService.release(criticalRegionContext);
        return false;
    }
}
